<template>
  <div>
    <div class="workspacecc" style="height: 100%">
      <el-container
        ref="listWarp"
        style="height: 100%; background-color: #fff"
        v-loading="addLoading"
      >
        <el-main class="page-main container maxWidth" style="height: 100%">
          <div
            class="content"
            style="width: 700px; margin: 0 auto; border-radius: 6px"
          >
            <el-form
              :model="form"
              :rules="rules"
              class="demo-ruleForm"
              label-width="100px"
              ref="form"
            >
              <el-form-item label="发布类型" prop="type">
                <el-radio-group size="small" v-model="form.type">
                  <el-radio-button class="left" label="1">失物</el-radio-button>
                  <el-radio-button class="left" label="2">招领</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="联系人" prop="contacts">
                <el-input v-model="form.contacts"></el-input>
              </el-form-item>
              <el-form-item label="联系电话" prop="contactNumber">
                <el-input v-model="form.contactNumber"></el-input>
              </el-form-item>
              <el-form-item label="所在地址" prop="address">
                <el-input v-model="form.address"></el-input>
              </el-form-item>
              <el-row>
                <el-form-item label="物品分类" prop="itemId">
                  <el-select
                    v-model="form.itemId"
                    style="width: 100%"
                    placeholder="请选择物品分类"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-form-item label="发帖标题" prop="title">
                <el-input v-model="form.title"></el-input>
              </el-form-item>
              <el-form-item label="物品描述" prop="description">
                <el-input type="textarea" v-model="form.description"></el-input>
              </el-form-item>
              <el-form-item label="图片">
                <el-upload
                  :class="{ show: uploadDisabled && imgUrl.length > 5 }"
                  class="upload-demo"
                  action="/api/file/upload"
                  list-type="picture-card"
                  :data="Imgdata"
                  :headers="headers"
                  accept="image/*"
                  :on-preview="handlePreview"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :on-progress="onProgresspc"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="6"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-form>
            <div
              class="dialog-footer"
              style="background: #fff; border-top: none; text-align: center"
            >
              <el-button @click="cencal">取 消</el-button>
              <el-button @click="addBtn('form')" type="primary">确定</el-button>
            </div>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import { microLostApi } from "@/api/micro/microLost";
import { compression } from "@/itsoftUI/utils/imgCompression";
import { validateEmail, validateMobile } from "@/itsoftUI/utils/validate";
import Token from "@/itsoftUI/auth/token.js";

export default {
  data() {
    return {
      options: [],
      addLoading: false,
      imgList: [],
      fileList: [],
      imgUrl: [],
      uploadDisabled: true,
      headers: {
        Token: "",
        TokenKey: "",
      },
      Imgdata: {
        system: "micro",
      },
      // config: 'http://10.2.42.166:8080',
      form: {
        type: "1",
        contacts: "",
        contactNumber: "",
        address: "",
        itemId: "",
        itemName: "",
        title: "",
        description: "",
        images: "",
      },
      deptFlag: true,
      rules: {
        type: [
          {
            required: true,
            message: "请至少选择一个发布类型",
            trigger: "change",
          },
        ],
        contacts: [
          {
            required: true,
            message: "请填写联系人",
            trigger: "change",
          },
        ],
        contactNumber: [{ required: true, validator: validateMobile }],
        address: [
          {
            required: true,
            message: "请填写所在地址",
            trigger: "change",
          },
        ],
        itemId: [
          {
            required: true,
            message: "请至少选择一个物品分类",
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: "请填写发帖标题",
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            message: "请填写描述信息",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    cencal: function () {
      this.$refs.form.clearValidate();
      this.$refs.form.resetFields();
    },
    // 物品分类范围下拉
    GetScope: function () {
      let data = {
        isShowNoDept: "0",
      };
      microLostApi.List(data).then((res) => {
        if (res.status == "success") {
          this.options = res.data;
        }
      });
    },
    addBtn: function (form) {
      this.addLoading = true;
      this.options.forEach((item) => {
        if (item.id == this.form.itemId) {
          this.form.itemName = item.name;
        }
      });
      let that = this;
      console.log(this.imgUrl, "imgUrl");
      this.form.images = this.imgUrl.join(",");
      let formData = JSON.stringify(this.form);
      this.$refs[form].validate(function (valid) {
        if (valid) {
          microLostApi
            .Save(formData)
            .then((res) => {
              if (res.status == "success") {
                that.$message.success("保存成功");
                that.addLoading = false;
                that.$refs.form.clearValidate();
                that.$refs.form.resetFields();
                that.fileList = [];
              }
            })
            .catch((err) => {
              that.$message.error("保存失败");
            });
        }
      });
    },
    upload: function () {
      $("#file").click();
    },
    handlePreview(e) {
      window.open(e.url, "_blank");
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        // `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
        //   files.length + fileList.length
        // } 个文件`
        "当前限制选择6个文件，超出选择范围"
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    beforeAvatarUpload(file) {
      this.headers.Token = Token.getToken();
      this.headers.TokenKey = Token.getTokenKey();
      let _this = this;
      return new Promise((resolve, reject) => {
        let image = new Image(),
          resultBlob = "";
        image.src = URL.createObjectURL(file);
        image.onload = () => {
          // 调用方法获取blob格式，方法写在下边
          resultBlob = compression(image, file);
          console.log(resultBlob);
          resolve(resultBlob);
        };
        image.onerror = () => {
          reject();
        };
      });
    },
    handleAvatarSuccess(file, fileList) {
      //图片上传成功
      this.uploadDisabled = true;
      this.imgUrl.push(file.data.path);
    },
    onProgresspc() {
      this.uploadDisabled = true;
    },
    handleRemove(file, fileList) {
      this.uploadDisabled = false;
      if (file.response) {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i] == file.response.data.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].url == file.url) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      }
      if (file.response) {
        for (var i = 0; i < this.imgUrl.length; i++) {
          if (this.imgUrl[i] == file.response.data.path) {
            this.imgUrl.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.imgUrl.length; i++) {
          if (file.url.indexOf(this.imgUrl[i]) != -1) {
            this.imgUrl.splice(i, 1);
            break;
          }
        }
      }
    },
    handleExceed(files, fileList) {
      this.$message.error("只允许上传六张图片");
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ？`);
    },
  },
  created: function () {
    this.GetScope();
  },
};
</script>

<style lang='scss' scoped>
.workspacecc {
  .el-radio-button {
    margin-right: 30px;
  }

  .left {
    border-left: 1px solid #dcdfe6;
  }

  .van-notice-bar {
    margin-top: 10px;
    background-color: #fff;
  }

  ::v-deep .show .el-upload--picture-card {
    display: none !important;
  }

  ::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 90px;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
    line-height: 90px;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item-status-label i {
    position: absolute;
    top: 0px;
    left: 14px;
  }
}
</style>
